package com.jackeysun.util

import android.os.Handler
import android.os.HandlerThread
import android.os.Looper

/**
 *   Created by sunxunchao on 2021/12/24.
 */

private val HANDLER_THREAD = HandlerThread("io").apply {
    start()
}

fun toIO(runnable: Runnable) {
    val ioHandler = Handler(HANDLER_THREAD.looper)
    ioHandler.post(runnable)
}

private val MAIN_HANDLER: Handler = Handler(Looper.getMainLooper())
fun toUI(runnable: Runnable) {
    if (isMainThread()) {
        runnable.run()
    } else {
        MAIN_HANDLER.post(runnable)
    }
}

fun switchThread(runnable: Runnable) {
    if (isMainThread()) {
        toIO(runnable)
    } else {
        toUI(runnable)
    }
}

fun isMainThread(): Boolean = Looper.getMainLooper() == Looper.myLooper()